//
//  JCWActiveTagView.swift
//  HengYouCai
//
//  Created by wll on 2017/11/10.
//  Copyright © 2017年 lwj. All rights reserved.
//  活动标签视图--代码 eg:双11 加息券活动

///默认预留标签数量 因为我是放在cell中 所以先预留好 免得一直创建 造成卡顿
private let tagNumber = 5

import UIKit

class JCWActiveTagView: UIView {

    ///标签背景色
    var tagBgColor: Color? = UIColor.red
    ///是否有白色边框
    var isHaveBorder: Bool? = false
    ///标签文字字符串 多个以","分割
    private var tagsStr: String? = ""
    ///所有tags的宽度
    var totoalWidth : CGFloat = 0
    

    ///赋值
    func tagsStr(_ tagStr: String?)  {
        
        ///隐藏tags
        self.subviews.forEach({$0.isHidden = true})
        self.isHidden = false
        self.tagsStr = tagStr ?? ""
        if !self.tagsStr!.isEmpty {
            totoalWidth = 0
            let strArr = self.tagsStr!.components(separatedBy: ",")
            for i in 1...strArr.count{
                let lab: UILabel? = self.viewWithTag(i) as? UILabel
                lab?.isHidden = false
                lab?.text = "\(strArr[i-1])   "
                
                totoalWidth += lab?.frame.size.width ?? 0
            }
            totoalWidth = totoalWidth + CGFloat(5.0 * CGFloat(strArr.count))
        }
    }
    
    
    ///标签背景色(默认红色) 是否有红色色边框(默认false)
    convenience init(_ tagBgColor: Color?, _ isHaveBorder: Bool?, _ tagsStr: String?) {
        self.init(frame: CGRect.zero)
        self.backgroundColor = UIColor.clear
        
        if let color = tagBgColor {
            self.tagBgColor = color
        }
        if let bool = isHaveBorder {
            self.isHaveBorder = bool
        }
        if let str = tagsStr {
            self.tagsStr = str
        }
        
        self.createCV()
    }
    
    func createCV() {
        for tag in 1...tagNumber {
            ///创建
            let lab = UILabel()
            lab.backgroundColor = self.tagBgColor
            lab.tag = tag
            lab.textAlignment = .center
            lab.textColor = ColorFromRGBHex_WL(0x9e7c31)
            lab.font = Font_WL(10)
            if self.isHaveBorder! {
                lab.layer.borderWidth = 0.5
                lab.layer.borderColor = Normal_RedColor.cgColor
            }
            self.addSubview(lab)
//            lab.sd_cornerRadiusFromHeightRatio = 0.5
//            lab.sd_cornerRadius = 5
            lab.setSingleLineAutoResizeWithMaxWidth(120)
            ///布局
            if tag == 1{
                _ = lab.sd_layout()
                .centerYEqualToView(self)?
                .heightIs(15)?
                .leftEqualToView(self)
            }else{
                let sufixView = self.viewWithTag(tag-1)
                _ = lab.sd_layout()
                .centerYEqualToView(self)?
                .heightIs(15)?
                .leftSpaceToView(sufixView,5)
            }
        }
        self.tagsStr(self.tagsStr)
    }
    
    
}











